package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.data.ResGoodsCreateData;
import com.cskaoyan.bean.data.ResGoodsDetailData;
import com.cskaoyan.bean.data.ResGoodsUpdateData;
import com.cskaoyan.bean.data.RespCatAndBrandData;
import com.cskaoyan.bean.vo.GoodsVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.InstanceUtil;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

public class GoodsServiceImpl implements GoodsService {
    @Override
    public CommonData<MarketGoods> list(Integer page, Integer limit, String sort,
                                        String order, String goodSn, String name, Integer goodsId) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketGoodsMapper marketGoodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        //开启分页
        PageHelper.startPage(page, limit);
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        //添加条件
        example.setOrderByClause("id" + " " + "desc");
        if (goodSn != null) {
            criteria.andGoodsSnEqualTo(goodSn);
        }
        if (name != null) {
            criteria.andNameEqualTo(name);
        }
        if (goodsId != null) {
            criteria.andIdEqualTo(goodsId);
        }
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(example);
        TransactionUtil.commit();
        return CommonData.data(new PageInfo(marketGoods));
    }

    @Override
    public void update(ResGoodsUpdateData data) {
        TransactionUtil.startTransaction();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MarketGoodsAttribute> attributes = data.getAttributes();
        MarketGoods goods = data.getGoods();
        List<MarketGoodsProduct> products = data.getProducts();

        Integer goodsId = goods.getId();

        //根据GoodId，修改
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketGoodsAttributeMapper attributeMapper = sqlSession.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attributesCriteria = attributeExample.createCriteria();
        attributesCriteria.andGoodsIdEqualTo(1110016);
        List<MarketGoodsAttribute> attributeOrders = attributeMapper.selectByExample(attributeExample);
        MarketGoodsAttribute attributeOrder = attributeOrders.get(0);
        //遍历orders，修改信息
        for (int i = 0; i < attributes.size(); i++) {
            attributeOrder.setAttribute(attributes.get(i).getAttribute());
            attributeOrder.setValue(attributes.get(i).getValue());
            attributeOrder.setAddTime(new Date());
            attributeOrder.setUpdateTime(new Date());
            attributeMapper.updateByPrimaryKey(attributeOrder);
        }

        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria goodsCriteria = goodsExample.createCriteria();
        goodsCriteria.andIdEqualTo(1110016);
        //先把该条商品查出
        MarketGoods goodsOrder = goodsMapper.selectByExample(goodsExample).get(0);
        //先判断传过来的数据那几条有
        Class<? extends MarketGoods> clazz = goods.getClass();
        List<String> list = InstanceUtil.getNoNullFields(goods);
        //将数据更新到Order里面
        goodsOrder = (MarketGoods) InstanceUtil.copyNonNullFields(list, goods, goodsOrder);
        //更新
        goodsMapper.updateByPrimaryKey(goodsOrder);

        MarketGoodsProductMapper productMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria productCriteria = productExample.createCriteria();
        productCriteria.andGoodsIdEqualTo(1110016);
        MarketGoodsProduct productOrder = productMapper.selectByExample(productExample).get(0);
        if (productOrder != null) {
            //添加products
            for (int i = 0; i < products.size(); i++) {
                List<String> noNullFields = InstanceUtil.getNoNullFields(products.get(0));
                InstanceUtil.copyNonNullFields(noNullFields, products.get(0), productOrder);
                productMapper.updateByPrimaryKey(productOrder);
            }
        }

        sqlSession.commit();
        sqlSession.close();



    }

    @Override
    public void delete(MarketGoods goods) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketGoodsMapper mapper = sqlSession.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(goods.getId());
        MarketGoods record = mapper.selectByExample(example).get(0);
        record.setDeleted(true);
        System.out.println(record);
        int i = mapper.updateByExample(record,example);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public ResGoodsDetailData detail(Integer id) {
        TransactionUtil.startTransaction();
        ResGoodsDetailData resGoodsDetailData = new ResGoodsDetailData();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        //根据商品id拿到五组数据

        //1.attributes
        MarketGoodsAttributeMapper attributeMapper = sqlSession.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attributeExampleCriteria = attributeExample.createCriteria();
        attributeExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(attributeExample);
        //2.goods
        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria goodsCriteria = goodsExample.createCriteria();
        goodsCriteria.andIdEqualTo(id);
        MarketGoods goods = goodsMapper.selectByExample(goodsExample).get(0);
        //3.categoryIds
        Integer categoryId = goods.getCategoryId();
        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);
        //4.products
        MarketGoodsProductMapper productMapper = sqlSession.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria productExampleCriteria = marketGoodsProductExample.createCriteria();
        productExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> products = productMapper.selectByExample(marketGoodsProductExample);

        //5.specifications
        MarketGoodsSpecificationMapper specificationMapper = sqlSession.getMapper(MarketGoodsSpecificationMapper.class);
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria specificationExampleCriteria = specificationExample.createCriteria();
        specificationExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExample(specificationExample);
        //封装到ResGoodsDetailData
        resGoodsDetailData.setAttributes(attributes);
        resGoodsDetailData.setCategoryIds(categoryIds);
        resGoodsDetailData.setGoods(goods);
        resGoodsDetailData.setProducts(products);
        resGoodsDetailData.setSpecifications(specifications);

        TransactionUtil.commit();
        return resGoodsDetailData;
    }

    @Override
    public RespCatAndBrandData catAndBrand() {
        TransactionUtil.startTransaction();
        RespCatAndBrandData respCatAndBrandData = new RespCatAndBrandData();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        //1.查询brands
        MarketBrandMapper brandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        MarketBrandExample brandExample = new MarketBrandExample();
        List<MarketBrand> brands = brandMapper.selectByExample(brandExample);
        //2.查询categorys
        MarketCategoryMapper categoryMapper = sqlSession.getMapper(MarketCategoryMapper.class);
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> categories = categoryMapper.selectByExample(categoryExample);
        //3.封装
        //封装brandList
        List<Map<String,Object>> brandList = new ArrayList<>();
        for (MarketBrand brand : brands) {
            Map<String,Object> map = new HashMap<>();
            map.put("value",brand.getId());
            map.put("label",brand.getName());
            brandList.add(map);
        }
        respCatAndBrandData.setBrandList(brandList);
        //封装categoriesList
        List<Map<String,Object>> categorieList = new ArrayList<>();
        for (MarketCategory category : categories) {
            Map<String,Object> map = new HashMap<>();
            map.put("children",category.getChildren());
            map.put("label",category.getName());
            map.put("value",category.getId());
            categorieList.add(map);
        }
        respCatAndBrandData.setCategoryList(categorieList);

        TransactionUtil.commit();
        return respCatAndBrandData;
    }

    public BaseRespVo create(GoodsVo goodsVo) {
        TransactionUtil.startTransaction();

        MarketGoods goods = goodsVo.getGoods();
        MarketGoodsProduct[] products = goodsVo.getProducts();
        MarketGoodsAttribute[] attributes = goodsVo.getAttributes();
        MarketGoodsSpecification[] specifications = goodsVo.getSpecifications();

        if (this.checkExistByName(goods.getName())) {
            return BaseRespVo.fail(611, "商品已经存在");
        }

        BigDecimal retailPrice = new BigDecimal(Integer.MAX_VALUE);
        for (MarketGoodsProduct product : products) {
            BigDecimal productPrice = product.getPrice();
            if (retailPrice.compareTo(productPrice) == 1) {
                retailPrice = productPrice;
            }
        }
        goods.setRetailPrice(retailPrice);


        MarketGoodsMapper marketGoodsMapper = TransactionUtil.getMapper(MarketGoodsMapper.class);
        goods.setDeleted(false);
       // goods.setGoodsSn(this.getLastId());
        marketGoodsMapper.insert(goods);

        int goodsId = getGoodsId(goods.getName());

        //marketGoodsMapper.insert(goods);

        MarketGoodsProductMapper marketGoodsProductMapper = TransactionUtil.getMapper(MarketGoodsProductMapper.class);

        for (MarketGoodsProduct product : products) {
            product.setId(null);

            product.setGoodsId(goodsId);

            marketGoodsProductMapper.insert(product);
        }

        MarketGoodsAttributeMapper marketGoodsAttributeMapper = TransactionUtil.getMapper(MarketGoodsAttributeMapper.class);
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goodsId);
            attribute.setId(null);
            marketGoodsAttributeMapper.insert(attribute);
        }



        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper = TransactionUtil.getMapper(MarketGoodsSpecificationMapper.class);


        for (MarketGoodsSpecification specification : specifications) {
            specification.setGoodsId(goodsId);
            specification.setId(null);

            marketGoodsSpecificationMapper.insert(specification);
        }

        TransactionUtil.commit();


        return BaseRespVo.ok();

    }

    private String getLastId() {
        MarketGoodsMapper mapper = TransactionUtil.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria();
        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);

        int maxId = 0;
        for (MarketGoods marketGood : marketGoods) {
            if(marketGood.getId()>maxId){
                maxId = marketGood.getId();
            }
        }
        return String.valueOf(maxId);
    }

    private int getGoodsId(String name) {
        MarketGoodsMapper mapper = TransactionUtil.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andNameEqualTo(name);
        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);
        MarketGoods marketGoods1 = marketGoods.get(0);
        return marketGoods1.getId();

    }


    private boolean checkExistByName(String name) {
        MarketGoodsMapper mapper = TransactionUtil.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andNameEqualTo(name);
        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);
        if (marketGoods.size() == 0) {
            return false;
        } else {
            return true;
        }
    }
}
